//
//  OneDetailViewController.m
//  Kaoshiti
//
//  Created by lanou3g on 15/10/22.
//  Copyright (c) 2015年 张蒙恩. All rights reserved.
//

#import "OneDetailViewController.h"
#import "AllTypeModel.h"
#import "OneDetailModel.h"
#import "OneDetailCell.h"
#import "AllTypeViewController.h"
#import "DB.h"
@interface OneDetailViewController ()<sentModel,UIAlertViewDelegate>
@property (nonatomic,strong)NSMutableArray *oneDetailArray;
@property (nonatomic,strong)AllTypeModel *upModel;
@end

@implementation OneDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"全部分类" style:UIBarButtonItemStylePlain target:self action:@selector(allTypePage:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"刷新" style:UIBarButtonItemStylePlain target:self action:@selector(upButton)];
   }

- (void)viewWillAppear:(BOOL)animated
{
        [self getNewView];
    self.title = self.allTypeModel.title;
    [self.tableView registerClass:[OneDetailCell class] forCellReuseIdentifier:@"cell"];
}

//跳转到allpage页面
- (void)allTypePage:(UIBarButtonItem *)button
{
    AllTypeViewController *allTPVC = [[AllTypeViewController alloc]init];
    allTPVC.modelDelegate = self;
    [self.navigationController pushViewController:allTPVC animated:YES];
}
//从数据库获取数据
- (void)getNewViewFromSqli
{
    if (self.allTypeModel == nil) {
        
        self.allTypeModel = [[AllTypeModel alloc]init];
        
        NSData *data = [[NSData alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Setup.json" ofType:nil]];
        NSMutableDictionary *allDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *typeArray = allDic[@"dataArray"];
        [self.allTypeModel setValuesForKeysWithDictionary:typeArray[0]];
        NSLog(@"%@",self.allTypeModel);
    }else{
        self.allTypeModel = self.upModel;
    }
    DB *manager = [DB manager];
    [manager openDB];
    [manager createTable];
    [manager selectAllModel];
    self.oneDetailArray = [[NSMutableArray alloc]initWithArray:[manager selectAllModel]];
    [manager closeDB];
}


//从网络获取数据
- (void)getNewView
{
    self.oneDetailArray = [[NSMutableArray alloc]init];
    if (self.allTypeModel == nil) {
        
        self.allTypeModel = [[AllTypeModel alloc]init];
        
        NSData *data = [[NSData alloc]initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Setup.json" ofType:nil]];
        NSMutableDictionary *allDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *typeArray = allDic[@"dataArray"];
        [self.allTypeModel setValuesForKeysWithDictionary:typeArray[0]];
        NSLog(@"%@",self.allTypeModel);
    }
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"http://www.to8to.com/mobileapp/zxhelper.php?action=getread&stype=%@&p=&id=3",self.allTypeModel.stype]];
    NSLog(@"%@",self.allTypeModel.stype);
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error|| !data ) {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *alte = [[UIAlertView alloc]initWithTitle:@"提示" message:@"数据请求失败,请刷新页面,或查看本地数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"本地数据", nil];
                [alte show];
            });
            return ;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSMutableArray *arr = dic[@"content"];
        DB *manager = [DB manager];
        [manager openDB];
        [manager createTable];
        [manager deleteAllModel];
        for (NSMutableDictionary *dic1 in arr) {
            NSLog(@"%@",dic1);
            OneDetailModel *model = [[OneDetailModel alloc]init];
            [model setValuesForKeysWithDictionary:dic1];
            [manager insertModel:model];
            [self.oneDetailArray addObject:model];
        }
        self.upModel = self.allTypeModel;
        [manager closeDB];
        [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:self waitUntilDone:YES];
    }];
    
    [dataTask resume];

}

- (void)upButton
{
    [self getNewView];
  UIAlertView *al = [[UIAlertView alloc]initWithTitle:@"" message:@"刷新成功0、0" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [al show];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.oneDetailArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   CGFloat height = [OneDetailCell heigthForModel:self.oneDetailArray[indexPath.row]];
    if (height < 110) {
        return 120;
    }else{
        return height;
    }
}

- (void)sentModel:(AllTypeModel *)model
{
    self.allTypeModel = model;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   OneDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    

     cell.alltypeModel = self.allTypeModel;
    OneDetailModel *model = self.oneDetailArray[indexPath.row];
    cell.oneDetailModel = model;
   
    return cell;
}
//提示框的选项
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (buttonIndex == 1) {
        [self upView];
    }
}
//更新本地数据
- (void)upView
{
    [self getNewViewFromSqli];
    self.title = self.allTypeModel.title;
    [self.tableView reloadData];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
